package com.gqyin.demo.service.impl;

import com.gqyin.demo.common.ResponseCode;
import com.gqyin.demo.dao.UserRepository;
import com.gqyin.demo.domain.User;
import com.gqyin.demo.domain.UserQueryParam;
import com.gqyin.demo.exception.ResourceNotFoundException;
import com.gqyin.demo.exception.TestException;
import com.gqyin.demo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * @author guiqing.yin
 * 2024-03-28 16:31
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User, String> implements UserService {

    public static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        super(userRepository);
        this.userRepository = userRepository;
    }

    @Override
    public Page<User> query(@NotNull UserQueryParam queryParam) {
        return userRepository.query(queryParam);
    }

    @Override
    public User findByName(@NotBlank String name) {
        Validate.notBlank(name, "'name' must not be blank");
        User user = userRepository.findByName(name);
        if (user == null) {
            String message = String.format("The user with name=%s DOES NOT EXIST", name);
            throw new ResourceNotFoundException(message);
        }
        return user;
    }

    @Override
    public User save(@Valid User user) {
        User existing = userRepository.findByName(user.getName());
        if (existing != null) {
            String message = String.format("The user with name=%s ALREADY EXISTS", user.getName());
            throw new TestException(message, ResponseCode.ALREADY_EXISTS);
        }
        return super.save(user);
    }

    @Override
    public User updateById(@NotNull User user, @NotBlank String id) {
        if (StringUtils.isNotBlank(user.getName())) {
            User existing = userRepository.findByName(user.getName());
            if (existing != null && !id.equals(existing.getId())) {
                String message = String.format("The user with name=%s ALREADY EXISTS", user.getName());
                throw new TestException(message, ResponseCode.ALREADY_EXISTS);
            }
        }
        return super.updateById(user, id);
    }
}
